package IOTWeb.com.handler;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.utils.MGUtil;
import IOTWeb.com.utils.Utils;

/**
 * @author JaridLi
 * 从mongodb数据库得到文件
 */
public class DownloadFromMongoHandler implements HttpHandler{

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		MGUtil mgUtil = new MGUtil();
		Utils utils = new Utils();
		
		// 获取文件名
		String queryString = exchange.getRequestURI().getQuery();
		Map<String, String> queryStringInfo = utils.formData2Dic(queryString);
		String fileName = queryStringInfo.get("fileName");
		
		byte[] download = null;
		// 下载
		try {
			download = mgUtil.download(fileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Headers responseHeaders = exchange.getResponseHeaders();
		utils.setResponseBinary(responseHeaders, fileName);
		exchange.sendResponseHeaders(200, download.length);
		exchange.getResponseBody().write(download);
		exchange.close();
	}
	
}
